package cvut.cz.via.android;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.URI;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import cvut.cz.via.android.settings.Setting;
import cvut.cz.via.android.users.User;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity {
	
	private EditText usernameEditText;
	private EditText passwordEditText;
	private Button loginButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    	StrictMode.setThreadPolicy(policy);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_activity);
		//startMainMenu();
		setUpViews();		
	}
	
	
	private void setUpViews() {
		
		usernameEditText = (EditText) findViewById(R.id.login_activity_username_edit_text);
		passwordEditText = (EditText) findViewById(R.id.login_activity_password_edit_text);
		
		loginButton = (Button) findViewById(R.id.login_activity_login_button);
		
		loginButton.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {
				login();
			}
		});	
	}

	protected void login() {
		BufferedReader reader = null;
		String url = "http://vychodniarivia.appspot.com/userlogin/" + usernameEditText.getEditableText().toString().trim() + "-" + passwordEditText.getEditableText().toString().trim();
		try {
		    HttpClient httpclient = new DefaultHttpClient();
		    HttpResponse response = httpclient.execute(new HttpGet(new URI(url)));
		    reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		    String code = reader.readLine().trim();
			if(code.equals("OK")) {
				StudyMaterialsApplication sma = getStudyMaterialsApplication();
				User _user = new User(usernameEditText.getEditableText().toString().trim(), passwordEditText.getEditableText().toString().trim());
				Log.d("USER_CREATION", "1");
				ArrayList<Setting> settings = new ArrayList<Setting>();
				settings.add(new Setting("Notifications", true));
				settings.add(new Setting("Automatic downloads", false));
				settings.add(new Setting("Sync with Dropbox", false));
				settings.add(new Setting("Sync with GoogleDocs", false));
				Log.d("USER_CREATION", "2");
				_user.setUserSettings(settings);
				Log.d("USER_CREATION", "3");
				Log.d("USER_TO_STRING", _user.getUserSettings().toString());
				sma.user = _user;
				ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
				ObjectOutput out = new ObjectOutputStream(bos);
				out.writeObject(_user);
				byte[] buf = bos.toByteArray();
		        FileOutputStream fos = this.openFileOutput("config.dat", Context.MODE_PRIVATE);
		        fos.write(buf);
		        fos.close();
		        Log.d("USER_CREATED", _user.toString());
				Intent intent = new Intent(LoginActivity.this, MainMenuActivity.class);
				startActivityForResult(intent, 1);
			} else {
				Intent intent = new Intent(LoginActivity.this, LoginFailedActivity.class);
				startActivity(intent);
			}
		} catch (Exception e) {
			Log.d("EXCEPTION", e.getLocalizedMessage());
		}
	}
	
	

	private StudyMaterialsApplication getStudyMaterialsApplication() {
		StudyMaterialsApplication sma = (StudyMaterialsApplication)getApplication();
		return sma;
	}
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		finish();
	}
	

}
